﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using com.IronOne.BoardPACWinApp.View.Page;
using com.IronOne.BoardPACWinAppBO.Agenda;
using com.IronOne.BoardPACWinAppBO.Category;
using com.IronOne.BoardPACWinAppBO.General;
using com.IronOne.BoardPACWinAppBO.Meeting;
using com.IronOne.BoardPACWinAppService.Auth;
using com.IronOne.BoardPACWinAppService.Category;
using com.IronOne.BoardPACWinAppUtil.Enums;
using com.IronOne.BoardPACWinAppUtil.Util;

namespace com.IronOne.BoardPACWinApp.Helpers
{
    public class CommonHelper
    {
        private static CommonHelper _commonHelper;

        public static CommonHelper GetInstance()
        {
            return _commonHelper ?? (_commonHelper = new CommonHelper());
        }

        public async Task<ListHelperDataModel> PopulateCategoryListView(List<CategoryModel> globalCategoryList,
            ICategoryService categoryService, CategoryModel globalCategorySelectedItem, ListView categoryListView,
            int globalSubCategoryId, SubCategoryModel globalSubCategorySelectedItem)
        {
            try
            {
                globalCategoryList = await categoryService.GetCategories();
                if (globalCategoryList != null && globalCategoryList.Count > 0)
                {
                    globalCategoryList.Insert(0,
                        new CategoryModel {CategoryId = -1, CategoryName = "All", ShortName = "All"});
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        // Your UI update code goes here!
                        CategoryModel cmo = null;
                        if (globalCategorySelectedItem != null)
                        {
                            cmo = new CategoryModel
                            {
                                Actions = globalCategorySelectedItem.Actions,
                                CategoryId = globalCategorySelectedItem.CategoryId,
                                CategoryName = globalCategorySelectedItem.CategoryName,
                                CategoryOrder = globalCategorySelectedItem.CategoryOrder,
                                Info = globalCategorySelectedItem.Info,
                                LastUpdatedDateTime = globalCategorySelectedItem.LastUpdatedDateTime,
                                ShortName = globalCategorySelectedItem.ShortName
                            };
                        }

                        categoryListView.DataContext = globalCategoryList;
                        if (cmo == null) categoryListView.SelectedIndex = 0;
                        else
                        {
                            try
                            {
                                categoryListView.SelectedIndex =
                                    globalCategoryList.FindIndex(x => x.CategoryId == cmo.CategoryId);
                            }
                            catch (Exception)
                            {
                                //If selectd category above is deleted from backend then first item will be selected 
                                categoryListView.SelectedIndex = 0;
                                globalSubCategoryId = -1;
                                globalSubCategorySelectedItem = null;
                            }
                        }

                        if (categoryListView.SelectedIndex == -1)
                        {
                            categoryListView.SelectedIndex = 0;
                        }
                    });
                }

                var lhdm = new ListHelperDataModel
                {
                    GlobalCategoryList = globalCategoryList,
                    GlobalCategorySelectedItem = globalCategorySelectedItem,
                    GlobalSubCategoryId = globalSubCategoryId,
                    GlobalSubCategorySelectedItem = globalSubCategorySelectedItem
                };
                return lhdm;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async Task<ListHelperDataModel> CommonCategoryListViewSelectionChanged(ListView categoryListView,
            ICategoryService categoryService, ListView subCategoryListView,
            SubCategoryModel globalSubCategorySelectedItem)
        {
            try
            {
                var globalCategoryId = -1;
                List<SubCategoryModel> globalSubCategoryList;
                var globalCategorySelectedItem = categoryListView.SelectedItem as CategoryModel;
                if (globalCategorySelectedItem != null)
                {
                    globalCategoryId = globalCategorySelectedItem.CategoryId;
                }
                
                if (globalCategoryId != -1)
                    globalSubCategoryList = await categoryService.GetSubCategoriesByCategoryId(globalCategoryId);
                else
                    globalSubCategoryList = null;

                subCategoryListView.DataContext = globalSubCategoryList;

                if (globalSubCategoryList != null && globalSubCategoryList.Count > 0)
                {
                    if (globalSubCategorySelectedItem == null)
                        subCategoryListView.SelectedIndex = -1;
                    else
                        subCategoryListView.SelectedIndex =
                            globalSubCategoryList.FindIndex(
                                x => x.SubCategoryId == globalSubCategorySelectedItem.SubCategoryId);
                }

                var lhdm = new ListHelperDataModel
                {
                    GlobalCategorySelectedItem = globalCategorySelectedItem,
                    GlobalCategoryId = globalCategoryId,
                    GlobalSubCategoryList = globalSubCategoryList,
                    GlobalSubCategorySelectedItem = globalSubCategorySelectedItem
                };
                return lhdm;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public ListHelperDataModel CommonSubCategoryListViewSelectionChanged(ListView subCategoryListView)
        {
            try
            {
                #region SubCategoryListViewSelectionChanged
                int globalSubCategoryId;
                var subCategoryId = -1;
                var globalSubCategorySelectedItem = (SubCategoryModel)subCategoryListView.SelectedItem;

                if (globalSubCategorySelectedItem != null)
                {
                    subCategoryId = globalSubCategorySelectedItem.SubCategoryId;
                }
                globalSubCategoryId = subCategoryId;

                var lhdm = new ListHelperDataModel()
                {
                    GlobalSubCategoryId = globalSubCategoryId,
                    GlobalSubCategorySelectedItem = globalSubCategorySelectedItem
                };
                return lhdm;
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async Task CommonMeetingGridViewSelectionChanged(GridView meetingGridView, ICategoryService categoryService, INavigationService navigationService, List<CategoryModel> globalCategoryList, List<SubCategoryModel> globalSubCategoryList, int globalCategoryId, int globalSubCategoryId)
        {
            try
            {
                var am = new AgendaModel { SelectedMeeting = (MeetingModel)meetingGridView.SelectedItem };
                if (am.SelectedMeeting == null) return;

                Global.IsBoardSecrartary = am.SelectedMeeting.Actions.Contains("UpdateMeetingPresence_XML");

                am.SelectedCategory = globalCategoryId == -1 ? globalCategoryList.FirstOrDefault(x => x.CategoryId == am.SelectedMeeting.CategoryId) : globalCategoryList.FirstOrDefault(x => x.CategoryId == globalCategoryId);

                if (globalCategoryId != -1 && globalSubCategoryId == -1)
                    am.SelectedSubCategory = globalSubCategoryList.FirstOrDefault(x => x.SubCategoryId == am.SelectedMeeting.SubCategoryId);
                else if (globalCategoryId == -1 && globalSubCategoryId == -1)
                {
                    var scModel = await categoryService.GetSubCategoriesByCategoryId(am.SelectedMeeting.CategoryId);
                    am.SelectedSubCategory = scModel.FirstOrDefault(x => x.SubCategoryId == am.SelectedMeeting.SubCategoryId);
                }
                else
                    am.SelectedSubCategory = globalSubCategoryList.FirstOrDefault(x => x.SubCategoryId == globalSubCategoryId);

                navigationService.NavigateTo(typeof(AgendaPage), am);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async Task<ListHelperDataModel> RefereshSubCategoryListView(ICategoryService categoryService, int globalCategoryId, List<SubCategoryModel> globalSubCategoryList, ListView subCategoryListView, SubCategoryModel globalSubCategorySelectedItem)
        {
            try
            {
                globalSubCategoryList = await categoryService.GetSubCategoriesByCategoryId(globalCategoryId);

                await
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        // Your UI update code goes here!
                        subCategoryListView.DataContext = globalSubCategoryList;
                        if (globalSubCategoryList == null || globalSubCategoryList.Count <= 0) return;

                        if (globalSubCategorySelectedItem == null)
                            subCategoryListView.SelectedIndex = -1;
                        else
                        {
                            try { subCategoryListView.SelectedIndex = globalSubCategoryList.FindIndex(x => x.SubCategoryId == globalSubCategorySelectedItem.SubCategoryId); }
                            catch (Exception)
                            {
                                //If the above selected sub category is deleted from backend then nothing will get selected
                                subCategoryListView.SelectedIndex = -1;
                            }
                        }
                    });

                var lhdm = new ListHelperDataModel()
                {
                    GlobalSubCategoryList = globalSubCategoryList
                };
                return lhdm;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async Task<List<MeetingModel>> CommonListViewUiManipulations(IAuthService authService, List<MeetingModel> meetings)
        {
            try
            {
                #region Meeting View UI Manipulations
                const string next = "Next";
                const string scheduled = "Scheduled";
                const string last = "Last";

                const string cirIconSrc = "ms-appx:///Assets/Images/MeetingsPage/Meetings_Refrash.png";
                const string path = "ms-appx:///Assets/Images/MeetingsPage/";
                DateTime today = DateTime.Now;

                var showCircularMeetingDate = await authService.GetSettingValueBySettingName(DatabaseType.UserDb, ApplicationConstants.UserDbSettingNames.ShowCircularMeetingDate);

                var inc = 1;
                var isOnce = false;
                foreach (var item in meetings)
                {
                    inc++;
                    if (item.MeetingType == 1) // Meeting == 0  |  Circular == 1
                    {
                        item.CircularIconSource = cirIconSrc;
                        item.MeetingName = item.MeetingName.Replace("(CIRCULAR)", "(Circular)");

                        if (showCircularMeetingDate != null && Convert.ToInt16(showCircularMeetingDate) == 0)
                        {
                            item.ShowCircularMeetingDate = Visibility.Collapsed;
                        }
                    }
                    else
                        item.MeetingName = item.MeetingName.Replace("(MEETING)", "(Meeting)");

                    item.MeetingLocationShowHide = !String.IsNullOrWhiteSpace(item.Venue) ? Visibility.Visible : Visibility.Collapsed;

                    if (item.IsTentative == 1)
                    {
                        item.DateDisplayText = "to be notified";
                        item.TimeDisplayPanelDisplay = Visibility.Collapsed;
                        item.DateDisplayPanelAlignment = HorizontalAlignment.Right;
                        item.DateDisplayPanelMargin = "0 0 0 0";
                    }
                    else
                    {
                        //Date display with the formatting
                        item.DateDisplayText = Utility.GetDate(item.Date).Date.ToString(Global.DateFormat);

                        //Time display
                        if (item.MeetingType == 1) //Circular
                        {
                            item.TimeDisplayPanelDisplay = Visibility.Collapsed;
                            item.DateDisplayPanelAlignment = HorizontalAlignment.Right;
                            item.DateDisplayPanelMargin = "0 0 0 0";
                        }
                        if (item.MeetingType == 0) //Meeting
                        {
                            item.TimeDisplayPanelDisplay = Visibility.Visible;
                            item.DateDisplayPanelAlignment = HorizontalAlignment.Center;
                            item.DateDisplayPanelMargin = "-30 0 0 0";

                            string tFormat = Utility.GetTimeFormat();
                            var start = DateTime.Parse(item.StartTime).ToString(tFormat);
                            var end = DateTime.Parse(item.EndTime).ToString(tFormat);
                            item.TimeDisplayText = start + " - " + end;
                        }
                    }

                    //Comments count display
                    if (item.CommentsCount > 0)
                    {
                        item.CommentIconShowHide = Visibility.Visible;
                        item.CommentsCountDisplay = item.CommentsCount.ToString();
                        if (item.CommentsCount > Utility.GetMaxCountDisplay())
                            item.CommentsCountDisplay = Utility.GetMaxCountDisplayOnUi();
                    }
                    else
                        item.CommentIconShowHide = Visibility.Collapsed;

                    switch (item.MeetingStatus)
                    {
                        case (byte)MeetingStatus.Next:
                            item.MeetingStatusIconSource = path + "Meetings_Next.png";
                            item.MeetingStatusDisplayText = next;
                            break;
                        case (byte)MeetingStatus.Schedule:
                            item.MeetingStatusIconSource = path + "Meetings_Scheduled.png";
                            item.MeetingStatusDisplayText = scheduled;
                            break;
                        case (byte)MeetingStatus.Last:
                            item.MeetingStatusIconSource = path + "Meetings_Last.png";
                            item.MeetingStatusDisplayText = last;
                            break;
                    }

                    switch (item.PaperNotificationStatus)
                    {
                        case (int)PapernotificationStatus.New:
                            item.MeetingStatusSideIconSource = path + "Meetings_SI_New.png";
                            item.MeetingStatusSideIconBgColor = "Black";
                            break;
                        case (int)PapernotificationStatus.Amended:
                            item.MeetingStatusSideIconSource = path + "Meetings_SI_Amended.png";
                            item.MeetingStatusSideIconBgColor = "Red";
                            break;
                        case (int)PapernotificationStatus.Read:
                            //item.MeetingStatusSideIconSource = path + "Meetings_SI_Downloded.png";
                            //item.MeetingStatusSideIconBgColor = "Green";
                            break;
                    }

                    item.TileBgColor = (inc % 2) == 1 ? "#EBF9FE" : "#F4FCFF";
                                        
                    if (!isOnce && item.Date >= today && item.MeetingType == 0 && item.MeetingStatus == (byte)MeetingStatus.Next)
                    {
                        isOnce = true;
                        item.StripBgColor = "#F15022";
                    }
                }

                return meetings;
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}